﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using DevExpress.Utils;
using System.IO;
using System.Collections;

using DevExpress.XtraEditors.Controls;
using QLTV.Database;

namespace QLTV.Forms.KhaiBao
{
    public partial class frmCrew : BaseForm
    {
        public delegate void SaveHandler(object sender, EventArgs e);
        public event SaveHandler SaveClick;
        public frmCrew()
        {
            InitializeComponent();
            this.SaveClick += ucAssignment1.saveAssignment;
            //this.ucAssignment1.btnCancelVisible = false;
            //this.ucAssignment1.btnSaveVisible = false;
        }
        public bool isNew { get; set; }
        public string crewid { get; set; }
        public string newCrewid { get; set; }
        AssignmentDataContext data = new AssignmentDataContext();
        private void load()
        {
            // TODO: This line of code loads data into the 'dsCrew.tblQuanHe' table. You can move, or remove it, as needed.

            // TODO: This line of code loads data into the 'dsCrew.tblLoaiHD' table. You can move, or remove it, as needed.
            this.tblLoaiHDTableAdapter.Fill(this.dsCrew.tblLoaiHD);
            // TODO: This line of code loads data into the 'dsCrew.tblSchoolName' table. You can move, or remove it, as needed.
            this.tblSchoolNameTableAdapter.Fill(this.dsCrew.tblSchoolName);
            // TODO: This line of code loads data into the 'dsCrew.tblRank' table. You can move, or remove it, as needed.
            this.tblRankTableAdapter.Fill(this.dsCrew.tblRank);
            // TODO: This line of code loads data into the 'dsRanking.tblRank' table. You can move, or remove it, as needed.

            this.tblVesselTypeTableAdapter.Fill(this.dsVessel.tblVesselType);
            // TODO: This line of code loads data into the 'dsVessel.tblFlag' table. You can move, or remove it, as needed.

            // TODO: This line of code loads data into the 'dsVessel.tblVessel' table. You can move, or remove it, as needed.
            this.tblVesselTableAdapter.Fill(this.dsVessel.tblVessel);
            // TODO: This line of code loads data into the 'dsCrew.tblExprience' table. You can move, or remove it, as needed.
            // TODO: This line of code loads data into the 'dsCrew.tblCertification' table. You can move, or remove it, as needed.
            this.tblCertificationTableAdapter.Fill(this.dsCrew.tblCertification);
            // TODO: This line of code loads data into the 'dsCrew.tblCourse' table. You can move, or remove it, as needed.
            this.tblCourseTableAdapter.Fill(this.dsCrew.tblCourse);
            // TODO: This line of code loads data into the 'dsCrew.tblEducationType' table. You can move, or remove it, as needed.
            this.tblEducationTypeTableAdapter.Fill(this.dsCrew.tblEducationType);
            // TODO: This line of code loads data into the 'dsCrew.tblImmigrationDoc' table. You can move, or remove it, as needed.
            this.tblImmigrationDocTableAdapter.Fill(this.dsCrew.tblImmigrationDoc);
            // TODO: This line of code loads data into the 'dsCrew.tblImmigrationCrew' table. You can move, or remove it, as needed.
            // TODO: This line of code loads data into the 'dsDiaChi.tblPhuongXa' table. You can move, or remove it, as needed.
            this.tblPhuongXaTableAdapter.Fill(this.dsDiaChi.tblPhuongXa);
            // TODO: This line of code loads data into the 'dsDiaChi.tblQuanHuyen' table. You can move, or remove it, as needed.
            this.tblQuanHuyenTableAdapter.Fill(this.dsDiaChi.tblQuanHuyen);
            // TODO: This line of code loads data into the 'dsDiaChi.tblTinhThanh' table. You can move, or remove it, as needed.
            this.tblTinhThanhTableAdapter.Fill(this.dsDiaChi.tblTinhThanh);
            // TODO: This line of code loads data into the 'dsTraining.tblTrainingCourse' table. You can move, or remove it, as needed.
            this.tblTrainingCourseTableAdapter.Fill(this.dsTraining.tblTrainingCourse);
            // TODO: This line of code loads data into the 'dsTraining.tblTrainingCrews' table. You can move, or remove it, as needed.
            this.vesselDetailTableAdapter.Fill(this.dsVessel.vesselDetail);


            loadAssignment();

        }
        private void loadAssignment()
        {
            ucAssignment1.rdoStatus.SelectedIndex = 4;
            if (isNew)
            {

                tblCrewBindingSource.AddNew();
                tblAccountCrewBindingSource.AddNew();
                txtNganHang.SelectedIndex = 0;
                //  txtNganHang.Text = "VIB";
                radMarialStatus.EditValue = "Single";
            }
            else
            {
                this.tblCrewTableAdapter.FillByID(this.dsCrew.tblCrew, crewid);
                //lay danh sach ma thuyen vien 
                List<string> crewList = new List<string>();
                crewList.Add(crewid);
                ucAssignment1.crewList = crewList;
                loadData();

                tblAssignment a = data.tblAssignments.SingleOrDefault(a1 => a1.nCrewid == crewid && a1.isActive == true);
                if (a != null)
                {
                    switch (a.cStatus.ToUpper())
                    {
                        case "ON BOARD":
                            ucAssignment1.rdoStatus.SelectedIndex = 0;
                            ucAssignment1.dDatetime1.DateTime = a.dEmbarked.Value;
                            ucAssignment1.dDatetime2.Value = a.nContract.Value;
                            ucAssignment1.dDatetime3.DateTime = a.dDuKienRoiTau.Value;
                            ucAssignment1.lkVessel.EditValue = a.nVesselId.Value;
                            break;
                        case "ON VACATION":
                            ucAssignment1.rdoStatus.SelectedIndex = 1;
                            ucAssignment1.dDatetime1.DateTime = a.dLeave.Value;
                            ucAssignment1.dDatetime2.Value = a.nRequest.Value;
                            ucAssignment1.dDatetime3.DateTime = a.dSanSangLenTau.Value;
                            break;
                        case "ON RESIGN":
                            ucAssignment1.rdoStatus.SelectedIndex = 2;
                            ucAssignment1.dDatetime3.DateTime = a.dCatHopDong.Value;
                            break;
                        case "ON RETIRE":
                            ucAssignment1.rdoStatus.SelectedIndex = 3;
                            ucAssignment1.dDatetime3.DateTime = a.dNghiHuu.Value;
                            break;
                        case "NEW CREW":
                            ucAssignment1.rdoStatus.SelectedIndex = 4;
                            ucAssignment1.dDatetime3.DateTime = a.dKyHopDong.Value;
                            break;
                        default:
                            break;
                    }
                }
            }
            //ẩn 2 nút 
            ucAssignment1.btnSaveVisible = false;
            ucAssignment1.btnCancelVisible = false;
        }
        private void frmCrew_Load(object sender, EventArgs e)
        {

            load();
        }

        QLTV.Database.dsCrewTableAdapters.tblNextIDTableAdapter tadNextID = new Database.dsCrewTableAdapters.tblNextIDTableAdapter();

        public string getCrewID()
        {

            tadNextID.Fill(dsCrew.tblNextID);
            tblCrewTableAdapter.Fill(dsCrew.tblCrew);
            //kiem tra next id o bang temp
            if (dsCrew.tblNextID.Rows.Count > 0)
            {
                var data = from crew in dsCrew.tblNextID.AsEnumerable()
                           orderby crew.Field<string>("NextID") descending
                           select crew.Field<string>("NextID");

                int maxID = Convert.ToInt32(data.First<string>());

                if (maxID > 0 && maxID < 10)
                {
                    return "000" + (maxID + 1).ToString();

                }
                if (maxID >= 10 && maxID < 100)
                {
                    return "00" + (maxID + 1).ToString();

                }
                if (maxID >= 100 && maxID < 1000)
                {
                    return "0" + (maxID + 1).ToString();

                }
                if (maxID >= 1000)
                {
                    return maxID.ToString();

                }
            }
            else
            {
                if (dsCrew.tblCrew.Rows.Count > 0)
                {
                    var data = from crew in dsCrew.tblCrew.AsEnumerable()
                               orderby crew.Field<string>("nCrewId").Substring(1) descending
                               select crew.Field<string>("nCrewId").Substring(1);

                    int maxID = Convert.ToInt32(data.First<string>());

                    if (maxID > 0 && maxID < 10)
                    {
                        return "000" + (maxID + 1).ToString();

                    }
                    if (maxID >= 10 && maxID < 100)
                    {
                        return "00" + (maxID + 1).ToString();

                    }
                    if (maxID >= 100 && maxID < 1000)
                    {
                        return "0" + (maxID + 1).ToString();

                    }
                    if (maxID >= 1000)
                    {
                        return maxID.ToString();

                    }
                }
                else
                    return "0001";
            }
            return "";
        }

        private void updateSource()
        {
            try
            {
                if (!end)
                {
                    tblCrewBindingSource.EndEdit();
                    tblImmigrationCrewBindingSource.EndEdit();
                    tblEducationBindingSource.EndEdit();
                    tblNhanXetCuaChuTauBindingSource.EndEdit();
                    tblExprienceBindingSource.EndEdit();
                    tblCertificateCrewBindingSource.EndEdit();
                    tblHDLDBindingSource.EndEdit();
                    tblQuanHeBindingSource.EndEdit();
                    tblAccountCrewBindingSource.EndEdit();
                    tblTrainingCrewsBindingSource.EndEdit();
                }



                tblCrewTableAdapter.Update(dsCrew.tblCrew);
                tblImmigrationCrewTableAdapter.Update(dsCrew.tblImmigrationCrew);
                tblEducationTableAdapter.Update(dsCrew.tblEducation);
                tblCertificateCrewTableAdapter.Update(dsCrew.tblCertificateCrew);
                tblNhanXetCuaChuTauTableAdapter.Update(dsCrew.tblNhanXetCuaChuTau);
                tblExprienceTableAdapter.Update(dsCrew.tblExprience);
                tblHDLDTableAdapter.Update(dsCrew.tblHDLD);
                tblQuanHeTableAdapter.Update(dsCrew.tblQuanHe);
                tblAccountCrewTableAdapter.Update(dsCrew.tblAccountCrew);
                tblTrainingCrewsTableAdapter.Update(dsTraining.tblTrainingCrews);


                tblRankingTableAdapter.Insert(Convert.ToInt32(lookupRan.EditValue), txtMaThuyenVien.Text, DateTime.Now);
                alertControl1.Show(this, rm.GetString("sMessageCaption", myCultureInfo), rm.GetString("sMessageSuccess", myCultureInfo));
                end = false;

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Đã có lỗi xảy ra" + ex.ToString(), "Thông báo");
            }

        }

        private void loadData()
        {

            this.tblImmigrationCrewTableAdapter.FillByCrewID(this.dsCrew.tblImmigrationCrew, crewid);
            this.tblEducationTableAdapter.FillByCrewID(dsCrew.tblEducation, crewid);
            this.tblCertificateCrewTableAdapter.FillByCrewID(dsCrew.tblCertificateCrew, crewid);
            this.tblNhanXetCuaChuTauTableAdapter.FillByCrewID(dsCrew.tblNhanXetCuaChuTau, crewid);
            this.tblExprienceTableAdapter.FillBy(this.dsCrew.tblExprience, crewid);
            this.tblRankingTableAdapter.FillByCrewID(this.dsCrew.tblRanking, crewid);
            this.tblQuanHeTableAdapter.FillByCrewID(this.dsCrew.tblQuanHe, crewid);
            this.tblHDLDTableAdapter.FillByCrewID(this.dsCrew.tblHDLD, crewid);
            this.tblAccountCrewTableAdapter.FillBy(this.dsCrew.tblAccountCrew, crewid);
            tblTrainingCrewsTableAdapter.FillByCrew(this.dsTraining.tblTrainingCrews, crewid);
            if (dsCrew.tblAccountCrew.Rows.Count == 0)
            {
                tblAccountCrewBindingSource.AddNew();
                txtNganHang.SelectedIndex = 0;
            }


        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dxValidationProvider1.Validate())
            {

                txtMaThuyenVien.Tag = txtMaThuyenVien.EditValue;
                //luu va dong
                if (txtMaThuyenVien.Text != "")
                {

                    updateSource();
                    SaveClick(sender, e);
                    //dsCrew.AcceptChanges();
                    this.Close();
                }
                else
                {
                    // dxErrorProvider1.SetError(lookupRan, "Bạn chưa chọn chức danh");

                    xtraTabControl1.SelectedTabPageIndex = 0;
                    lookupRan.Focus();
                    lookupRan.ShowPopup();
                }
            }
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //luu va them
            if (dxValidationProvider1.Validate())
            {
                if (txtMaThuyenVien.Text != "")
                {
                    updateSource();
                    SaveClick(sender, e);
                    newCrewid = getCrewID();
                    isNew = true;
                    crewid = newCrewid;
                    //them next id vao temp
                    tadNextID.Insert(newCrewid);
                    tblCrewBindingSource.AddNew();
                    txtNganHang.SelectedIndex = 0;

                    loadData();
                    xtraTabControl1.SelectedTabPageIndex = 0;

                }
                else
                {
                    xtraTabControl1.SelectedTabPageIndex = 0;
                    lookupRan.Focus();
                    lookupRan.ShowPopup();
                }
            }
        }

        #region Education

        private void xoaEducation_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewEducation.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblEducationBindingSource.RemoveCurrent();
                    tblEducationTableAdapter.Update(dsCrew.tblEducation);
                }
            }

        }
        private void repositoryItemButtonEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.IsLeft)
            {
                if (viewEducation.FocusedRowHandle > -1 && viewEducation.GetFocusedRowCellValue("bScanDoc") != DBNull.Value)
                {

                    string ext = viewEducation.GetFocusedRowCellValue("cExt").ToString();
                    string filename = String.Format("{0}{1}{2}", Path.GetTempPath(), DateTime.Now.Ticks, ext);
                    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                    BinaryWriter br = new BinaryWriter(fs);
                    br.Write((byte[])viewEducation.GetFocusedRowCellValue("bScanDoc"));
                    fs.Dispose();
                    System.Diagnostics.Process.Start(filename);

                }
            }
            else
            {
                dialogFile = new OpenFileDialog();
                if (dialogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    bnoidung = ReadFile(dialogFile.FileName);
                    ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = dialogFile.SafeFileName;
                }
            }
        }

        private void viewEducation_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewEducation.SetRowCellValue(e.RowHandle, viewEducation.Columns["cCrewID"], txtMaThuyenVien.EditValue.ToString());
            if (dialogFile != null)
            {
                FileInfo info = new FileInfo(dialogFile.FileName);
                viewEducation.SetRowCellValue(e.RowHandle, viewEducation.Columns["cExt"], info.Extension);
                viewEducation.SetRowCellValue(e.RowHandle, viewEducation.Columns["bScanDoc"], bnoidung);
            }

        }

        #endregion

        #region Certificate
        private void xoaCertificate_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            //&& viewCertificate.GetFocusedRowCellValue("bScanDoc") != DBNull.Value
            if (viewCertificate.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblCertificateCrewBindingSource.RemoveCurrent();
                    tblCertificateCrewTableAdapter.Update(dsCrew.tblCertificateCrew);
                }
            }
        }
        private void viewCertificate_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewCertificate.SetRowCellValue(e.RowHandle, viewCertificate.Columns["nCrewid"], txtMaThuyenVien.EditValue.ToString());

            if (dialogFile != null)
            {
                FileInfo info = new FileInfo(dialogFile.FileName);
                viewCertificate.SetRowCellValue(e.RowHandle, viewCertificate.Columns["cExt"], info.Extension);
                viewCertificate.SetRowCellValue(e.RowHandle, viewCertificate.Columns["bScanDoc"], bnoidung);
            }


            if (viewCertificate.GetRowCellValue(e.RowHandle, viewCertificate.Columns["dDateOfIssued"]) != DBNull.Value && viewCertificate.GetRowCellValue(e.RowHandle, viewCertificate.Columns["dDateOfExpire"]) != DBNull.Value)
            {

                DateTime dDateOfIssued = (DateTime)viewCertificate.GetRowCellValue(e.RowHandle, viewCertificate.Columns["dDateOfIssued"]);
                DateTime dexpired = (DateTime)viewCertificate.GetRowCellValue(e.RowHandle, viewCertificate.Columns["dDateOfExpire"]);
                if (dDateOfIssued > dexpired)
                {
                    e.ErrorText = rm.GetString("sDateCompare", myCultureInfo);
                    e.Valid = false;
                }
            }


        }
        private void repositoryItemButtonEdit3_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.IsLeft)
            {
                if (viewCertificate.FocusedRowHandle > -1 && viewCertificate.GetFocusedRowCellValue("bScanDoc") != DBNull.Value)
                {

                    string ext = viewCertificate.GetFocusedRowCellValue("cExt").ToString();
                    string filename = String.Format("{0}{1}{2}", Path.GetTempPath(), DateTime.Now.Ticks, ext);

                    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                    BinaryWriter br = new BinaryWriter(fs);
                    br.Write((byte[])viewCertificate.GetFocusedRowCellValue("bScanDoc"));
                    fs.Dispose();
                    System.Diagnostics.Process.Start(filename);

                }
            }
            else
            {
                dialogFile = new OpenFileDialog();
                if (dialogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    bnoidung = ReadFile(dialogFile.FileName);
                    ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = dialogFile.SafeFileName;
                }
            }

        }
        void insertCertificateRequired(int idRank, string crewid)
        {

            dsCertificate.tblCertificationRequireDataTable certificateRequuired = new dsCertificate.tblCertificationRequireDataTable();
            Database.dsCertificateTableAdapters.tblCertificationRequireTableAdapter tadRequired = new Database.dsCertificateTableAdapters.tblCertificationRequireTableAdapter();
            tadRequired.FillBy_RankId(certificateRequuired, idRank);
            ArrayList existID = new ArrayList();
            if (isNew)
                dsCrew.tblCertificateCrew.Rows.Clear();
            else
            {


                for (int i = 0; i < dsCrew.tblCertificateCrew.Rows.Count; i++)
                {
                    existID.Add(Convert.ToInt32(dsCrew.tblCertificateCrew.Rows[i]["nCertificationId"]));


                }
            }
            for (int i = 0; i < certificateRequuired.Rows.Count; i++)
            {

                if (!isNew && existID.Contains(certificateRequuired.Rows[i]["nCertificationId"]))
                {
                    continue;
                }
                DataRow row = dsCrew.tblCertificateCrew.NewRow();
                row["nCertificationId"] = certificateRequuired.Rows[i]["nCertificationId"];
                row["nCrewid"] = crewid;

                dsCrew.tblCertificateCrew.Rows.Add(row);
            }
            tblCertificateCrewBindingSource.DataSource = dsCrew.tblCertificateCrew;

        }
        #endregion

        #region Nhan xet cua chu tau

        OpenFileDialog dialogFile = null;
        byte[] bnoidung;

        private void filePath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            dialogFile = new OpenFileDialog();
            if (dialogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                bnoidung = ReadFile(dialogFile.FileName);
                ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = dialogFile.SafeFileName;
            }
        }
        public byte[] ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                int length = (int)fileStream.Length;
                buffer = new byte[length];
                int count;
                int sum = 0;


                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }



        private void viewNhanXet_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["nCrewID"], txtMaThuyenVien.EditValue.ToString());
            if (dialogFile != null)
            {
                FileInfo info = new FileInfo(dialogFile.FileName);
                viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["cExt"], info.Extension);
                viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["nSize"], info.Length / 1000);
                viewNhanXet.SetRowCellValue(e.RowHandle, viewNhanXet.Columns["pNoiDung"], bnoidung);
            }

            //   colpNoiDung
        }


        private void xoa_ButtonClick(object sender, ButtonPressedEventArgs e)
        {

            if (viewNhanXet.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblNhanXetCuaChuTauBindingSource.RemoveCurrent();
                }
            }
        }

        private void btnXem_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewNhanXet.FocusedRowHandle > -1 && viewNhanXet.GetFocusedRowCellValue("pNoiDung") != DBNull.Value)
            {
                string ext = viewNhanXet.GetFocusedRowCellValue("cExt").ToString();
                string filename = String.Format("{0}{1}{2}", Path.GetTempPath(), DateTime.Now.Ticks, ext);

                FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                BinaryWriter br = new BinaryWriter(fs);
                br.Write((byte[])viewNhanXet.GetFocusedRowCellValue("pNoiDung"));
                fs.Dispose();
                System.Diagnostics.Process.Start(filename);

            }
        }

        #endregion

        #region Experience



        private void bandExp_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate").ToString() != "" && bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate").ToString() != "")
            {
                TimeSpan d = ((DateTime)bandExp.GetRowCellValue(e.RowHandle, "dDisembarkedDate")).Date - ((DateTime)bandExp.GetRowCellValue(e.RowHandle, "dEmbarkedDate")).Date;
                double months = Math.Round((double)d.Days / 30, 1);
                if (months == 0)
                    months = 1;
                bandExp.SetRowCellValue(e.RowHandle, "fDuration", months);
            }
            bandExp.SetRowCellValue(e.RowHandle, bandExp.Columns["nCrewId"], txtMaThuyenVien.EditValue.ToString());
        }


        private void btnxoa_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (bandExp.FocusedRowHandle > -1)
            {
                tblExprienceBindingSource.RemoveCurrent();

            }
        }
        #endregion


        private void lookupRan_EditValueChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(lookupRan.EditValue.ToString()))
            {
                int idRank = Convert.ToInt32(lookupRan.EditValue);
                int idRankType = Convert.ToInt16(Convert.ToInt16(tblRankTableAdapter.RankTypeID(Convert.ToInt16(lookupRan.EditValue))));
                tblCrewTypeTableAdapter.FillByID(dsCrew.tblCrewType, idRankType);
                if (isNew)
                {
                    txtMaThuyenVien.EditValue = dsCrew.tblCrewType.Rows[0]["Prefix"].ToString().Trim() + newCrewid;
                    txtMaThuyenVien.Tag = txtMaThuyenVien.EditValue;
                }
                else
                    txtMaThuyenVien.EditValue = dsCrew.tblCrewType.Rows[0]["Prefix"].ToString().Trim() + crewid.Substring(1);

                insertCertificateRequired(idRank, txtMaThuyenVien.EditValue.ToString());
                List<string> crewList = new List<string>();
                crewList.Add(txtMaThuyenVien.EditValue.ToString());
                ucAssignment1.crewList = crewList;
            }

        }

        private void textEdit4_Properties_Leave(object sender, EventArgs e)
        {
            txtHo.EditValue = txtHo.EditValue.ToString().ToUpper();
        }

        private void textEdit5_Leave(object sender, EventArgs e)
        {
            ((TextEdit)sender).EditValue = ((TextEdit)sender).EditValue.ToString().ToUpper();
        }

        #region Ho chieu
        private void repositoryItemButtonEdit1_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewHoChieu.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblImmigrationCrewBindingSource.RemoveCurrent();

                }
            }
        }
        private void viewHoChieu_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column == colSTT)
            {
                e.DisplayText = Convert.ToString(e.RowHandle + 1);
            }
        }

        private void fileBrowse_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.IsLeft)
            {
                if (viewHoChieu.FocusedRowHandle > -1 && viewHoChieu.GetFocusedRowCellValue("bScanDoc") != DBNull.Value)
                {

                    string ext = viewHoChieu.GetFocusedRowCellValue("cExt").ToString();
                    string filename = String.Format("{0}{1}{2}", Path.GetTempPath(), DateTime.Now.Ticks, ext);

                    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                    BinaryWriter br = new BinaryWriter(fs);
                    br.Write((byte[])viewHoChieu.GetFocusedRowCellValue("bScanDoc"));
                    fs.Dispose();
                    System.Diagnostics.Process.Start(filename);

                }
            }
            else
            {
                dialogFile = new OpenFileDialog();
                if (dialogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    bnoidung = ReadFile(dialogFile.FileName);
                    ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = dialogFile.SafeFileName;
                }
            }
        }
        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            viewHoChieu.SetRowCellValue(e.RowHandle, viewHoChieu.Columns["nCrewId"], txtMaThuyenVien.EditValue.ToString());

            if (dialogFile != null)
            {
                FileInfo info = new FileInfo(dialogFile.FileName);
                viewHoChieu.SetRowCellValue(e.RowHandle, viewHoChieu.Columns["cExt"], info.Extension);
                viewHoChieu.SetRowCellValue(e.RowHandle, viewHoChieu.Columns["bScanDoc"], bnoidung);
            }
            if (viewHoChieu.GetRowCellValue(e.RowHandle, viewHoChieu.Columns["dDateOfIssued"]) != DBNull.Value && viewHoChieu.GetRowCellValue(e.RowHandle, viewHoChieu.Columns["dDateOfExpiry"]) != DBNull.Value)
            {
                DateTime dDateOfIssued = (DateTime)viewHoChieu.GetRowCellValue(e.RowHandle, viewHoChieu.Columns["dDateOfIssued"]);
                DateTime dexpired = (DateTime)viewHoChieu.GetRowCellValue(e.RowHandle, viewHoChieu.Columns["dDateOfExpiry"]);

                if (dDateOfIssued > dexpired)
                {

                    e.ErrorText = "Ngày chưa đúng. ";
                    e.Valid = false;

                }
            }


        }

        #endregion

        #region HDLD
        private void viewHDLD_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewHDLD.SetRowCellValue(e.RowHandle, viewHDLD.Columns["CrewID"], txtMaThuyenVien.EditValue.ToString());
            if (viewHDLD.GetRowCellValue(e.RowHandle, viewHDLD.Columns["Ngày ký"]) != DBNull.Value)
            {
                DateTime dDateOfIssued = (DateTime)viewHDLD.GetRowCellValue(e.RowHandle, viewHDLD.Columns["Ngày ký"]);
                int year = (Int16)viewHDLD.GetRowCellValue(e.RowHandle, viewHDLD.Columns["Thời hạn"]);
                viewHDLD.SetRowCellValue(e.RowHandle, viewHDLD.Columns["Ngày hết hạn"], dDateOfIssued.AddYears(year));
            }
            else
            {
                e.ErrorText = rm.GetString("sDateCompare", myCultureInfo);
                e.Valid = false;
            }
        }



        private void xoaHDLD_ButtonClick(object sender, ButtonPressedEventArgs e)
        {

            if (viewHDLD.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblHDLDBindingSource.RemoveCurrent();
                }
            }
        }

        #endregion

        #region Phu thuoc
        private void viewPhuThuoc_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewPhuThuoc.SetRowCellValue(e.RowHandle, viewPhuThuoc.Columns["CrewID"], txtMaThuyenVien.EditValue.ToString());


            if (viewPhuThuoc.GetRowCellValue(e.RowHandle, viewPhuThuoc.Columns["Bắt đầu"]) != DBNull.Value)
            {

                if (viewPhuThuoc.GetRowCellValue(e.RowHandle, viewPhuThuoc.Columns["Kết thúc"]) != DBNull.Value)
                {
                    DateTime startDate = (DateTime)viewPhuThuoc.GetRowCellValue(e.RowHandle, viewPhuThuoc.Columns["Bắt đầu"]);
                    DateTime endDate = (DateTime)viewPhuThuoc.GetRowCellValue(e.RowHandle, viewPhuThuoc.Columns["Kết thúc"]);
                    if (startDate > endDate)
                    {
                        e.ErrorText = rm.GetString("sDateCompare", myCultureInfo);
                        e.Valid = false;
                    }

                }
            }



        }


        private void xoaPhuThuoc_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (viewPhuThuoc.FocusedRowHandle > -1)
            {
                if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblQuanHeBindingSource.RemoveCurrent();
                }
            }
        }
        #endregion

        #region Dia chi
        private void lookUpEdit4_EditValueChanged(object sender, EventArgs e)
        {

        }
        void autoFill()
        {
            if (checkEdit1.Checked)
            {
                luTinhThanhLienHe.EditValue = luTinhThanhThuongTru.EditValue;
                luQuanHuyenLienHe.EditValue = luQuanHuyenThuongTru.EditValue;
                luPhuongXaLienHe.EditValue = luPhuongXaThuongTru.EditValue;
                txtSoNhaLienHe.EditValue = txtSoNhaThuongTru.EditValue;
            }
        }
        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            autoFill();

        }


        private void luTinhThanhThuongTru_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmTinhThanh f = new frmTinhThanh();
                f.ShowDialog();
                tblTinhThanhTableAdapter.Fill(dsDiaChi.tblTinhThanh);
                tblTinhThanhBindingSource.MoveFirst();
            }
        }

        private void luTinhThanhLienHe_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmTinhThanh f = new frmTinhThanh();
                f.ShowDialog();
                tblTinhThanhTableAdapter.Fill(dsDiaChi.tblTinhThanh);
                tblTinhThanhBindingSource.MoveFirst();

            }
        }

        private void luQuanHuyenThuongTru_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmQuanHuyen f = new frmQuanHuyen();
                f.ShowDialog();
                tblQuanHuyenTableAdapter.Fill(dsDiaChi.tblQuanHuyen);
                tblQuanHuyenBindingSource.MoveFirst();

            }
        }

        private void luQuanHuyenLienHe_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmQuanHuyen f = new frmQuanHuyen();
                f.ShowDialog();
                tblQuanHuyenTableAdapter.Fill(dsDiaChi.tblQuanHuyen);
                tblQuanHuyenBindingSource.MoveFirst();

            }
        }

        private void luPhuongXaThuongTru_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmPhuongXa f = new frmPhuongXa();
                f.ShowDialog();
                tblPhuongXaTableAdapter.Fill(dsDiaChi.tblPhuongXa);
                tblPhuongXaBindingSource.MoveFirst();

            }
        }

        private void luPhuongXaLienHe_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmPhuongXa f = new frmPhuongXa();
                f.ShowDialog();
                tblPhuongXaTableAdapter.Fill(dsDiaChi.tblPhuongXa);
                tblPhuongXaBindingSource.MoveFirst();

            }
        }
        #endregion

        private void luTinhThanhThuongTru_EditValueChanged(object sender, EventArgs e)
        {
            //if (((LookUpEdit)sender).EditValue != DBNull.Value)
            //{
            //    int maTinh = (int)((LookUpEdit)sender).EditValue;
            //    tblQuanHuyenTableAdapter.FillBy(dsDiaChi.tblQuanHuyen, maTinh);
            //    autoFill();
            //}
        }

        private void luQuanHuyenThuongTru_EditValueChanged(object sender, EventArgs e)
        {
            //if (((LookUpEdit)sender).EditValue != DBNull.Value)
            //{
            //    int maQuan = (int)((LookUpEdit)sender).EditValue;
            //    tblPhuongXaTableAdapter.FillBy(dsDiaChi.tblPhuongXa, maQuan);
            //    autoFill();
            //}

        }

        private void luPhuongXaThuongTru_EditValueChanged(object sender, EventArgs e)
        {
            //  autoFill();
        }

        private void txtSoNhaThuongTru_EditValueChanged(object sender, EventArgs e)
        {
            // autoFill();
        }



        private void checkUnlimited_CheckedChanged(object sender, EventArgs e)
        {

            if (viewCertificate.GetRowCellValue(viewCertificate.FocusedRowHandle, viewCertificate.Columns["IsUnlimited"]) != DBNull.Value)
                if ((bool)viewCertificate.GetRowCellValue(viewCertificate.FocusedRowHandle, viewCertificate.Columns["IsUnlimited"]))
                    viewCertificate.SetRowCellValue(viewCertificate.FocusedRowHandle, viewCertificate.Columns["dDateOfExpire"], null);

        }


        private void viewTraining_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            viewTraining.SetRowCellValue(e.RowHandle, viewTraining.Columns["nCrewId"], txtMaThuyenVien.EditValue.ToString());
            viewTraining.SetRowCellValue(e.RowHandle, viewTraining.Columns["isConfirm"], true);

        }
        bool end = false;

        private void frmCrew_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.End)
            {
                if (XtraMessageBox.Show(rm.GetString("sHasChange", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    tblCrewBindingSource.EndEdit();
                    tblImmigrationCrewBindingSource.EndEdit();
                    tblEducationBindingSource.EndEdit();
                    tblNhanXetCuaChuTauBindingSource.EndEdit();
                    tblExprienceBindingSource.EndEdit();
                    tblCertificateCrewBindingSource.EndEdit();
                    tblHDLDBindingSource.EndEdit();
                    tblQuanHeBindingSource.EndEdit();
                    tblAccountCrewBindingSource.EndEdit();
                    tblTrainingCrewsBindingSource.EndEdit();
                    end = true;
                }

            }
        }

        private void btnXoaTraining_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
            {
                tblTrainingCrewsBindingSource.RemoveCurrent();

            }
        }

        private void viewCertificate_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column == stt)
            {
                e.DisplayText = Convert.ToString(e.RowHandle + 1);
            }
        }

        private void cmdImportCertificate_Click(object sender, EventArgs e)
        {
            if (lookupRan.EditValue != DBNull.Value)
            {
                int idRank = Convert.ToInt32(lookupRan.EditValue);
                insertCertificateRequired(idRank, txtMaThuyenVien.EditValue.ToString());
            }
        }

        private void viewEducation_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void viewEducation_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column == colIsCurrent)
            {
                if ((bool)e.Value)
                {
                    for (int i = 0; i < dsCrew.tblEducation.Rows.Count; i++)
                    {
                        if (i != e.RowHandle)
                            viewCertificate.SetRowCellValue(i, e.Column, false);
                    }

                }
            }
        }

        private void txtSoNhaLienHe_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            frmDiaChi f = new frmDiaChi();
            f.ShowDialog();
            if (f.ListId != null)
            {
                luTinhThanhThuongTru.EditValue = f.ListId.ToArray()[0];
                luQuanHuyenThuongTru.EditValue = f.ListId.ToArray()[1];
                luPhuongXaThuongTru.EditValue = f.ListId.ToArray()[2];
            }

        }

        private void txtSoNhaLienHe_ButtonClick_1(object sender, ButtonPressedEventArgs e)
        {
            frmDiaChi f = new frmDiaChi();
            f.ShowDialog();
            if (f.ListId != null)
            {
                luTinhThanhLienHe.EditValue = f.ListId.ToArray()[0];
                luQuanHuyenLienHe.EditValue = f.ListId.ToArray()[1];
                luPhuongXaLienHe.EditValue = f.ListId.ToArray()[2];
            }
        }

        private void lookupSchool_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                frmSchool f = new frmSchool();
                f.ShowDialog();
                tblSchoolNameTableAdapter.Fill(dsCrew.tblSchoolName);
            }
        }

        private void số_BHXHTextEdit_Leave(object sender, EventArgs e)
        {
            if (tblAccountCrewTableAdapter.CheckBHXH(số_BHXHTextEdit.EditValue.ToString()).Rows.Count > 0)
            {
                XtraMessageBox.Show("Số BHXH đã tồn tại", "Cảnh báo", MessageBoxButtons.OK);
                số_BHXHTextEdit.EditValue = "";
            }
        }

        private void số_BHXHTextEdit_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void số_TK_Ngân_hàngTextEdit_Leave(object sender, EventArgs e)
        {
            if (tblAccountCrewTableAdapter.CheckTK(số_TK_Ngân_hàngTextEdit.EditValue.ToString()).Rows.Count > 0)
            {
                XtraMessageBox.Show("Số TK Ngân hàng đã tồn tại", "Cảnh báo", MessageBoxButtons.OK);
                số_TK_Ngân_hàngTextEdit.EditValue = "";
            }
        }

        private void mã_số_thuếTextEdit_Leave(object sender, EventArgs e)
        {
            if (tblAccountCrewTableAdapter.CheckMST(mã_số_thuếTextEdit.EditValue.ToString()).Rows.Count > 0)
            {
                XtraMessageBox.Show("Số MST đã tồn tại", "Cảnh báo", MessageBoxButtons.OK);
                mã_số_thuếTextEdit.EditValue = "";
            }
        }



    }
}
